package com.saltedfish.tool.ui.calendar

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import cn.droidlover.xdroidmvp.event.BusProvider
import cn.droidlover.xdroidmvp.mvp.XFragment
import cn.droidlover.xdroidmvp.util.DateUtils
import com.saltedfish.tool.R
import com.saltedfish.tool.dao.AppDataUtils
import com.saltedfish.tool.dao.DayDBDao
import com.saltedfish.tool.dao.FlagInfoDao
import com.saltedfish.tool.dao.SubFlagModelDao
import com.saltedfish.tool.dialog.UIFlagDoneDialog
import com.saltedfish.tool.dialog.UIUpdateTimeDialog
import com.saltedfish.tool.model.DayTable
import com.saltedfish.tool.model.ModelInfo
import com.saltedfish.tool.present.XFP
import kotlinx.android.synthetic.main.fragment_beforeday.*
import kotlinx.android.synthetic.main.fragment_beforeday.mRecyclerView
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

class FragmentBeforeday : XFragment<XFP>(), View.OnClickListener {

    companion object {
        fun newInstance(): FragmentBeforeday {
            return FragmentBeforeday()
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_beforeday
    }

    override fun initData(savedInstanceState: Bundle?) {
        var database = AppDataUtils.initRoom(context)
        dayDBDao = database.dayDBDao()
        subFlagModelDao = database.subFlagDao()
        flagModelDao = database.flagInfoDao()

    }

    override fun loadData() {
        super.loadData()
        showTopData()

    }

    //显示顶部数据资源
    private fun showTopData() {
       // initDataShow()

    }

    override fun newP(): XFP? {
        return null
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btn_create -> {

            }

        }
    }


    var cal: Calendar? = null
    private var dayLists: MutableList<DayTable> = ArrayList()
    private var linearLayoutManager: LinearLayoutManager? = null
    private var adapter: CalendarAdapter? = null
    var dayDBDao: DayDBDao? = null
    var subFlagModelDao: SubFlagModelDao? = null
    var flagModelDao: FlagInfoDao? = null

    private var beforeday: String? = null

    override fun onResume() {
        super.onResume()

        cal = Calendar.getInstance()
        cal!!.time =  Date()
        val sdf = SimpleDateFormat("yyyy-MM-dd")
         beforeday = DateUtils.getBeforedayTime(cal,sdf)


        updateCalendar()

    }

    //刷新列表
    private fun updateCalendar() {
        dayLists.clear()
        dayLists =  dayDBDao!!.getByDay(beforeday)
        if(dayLists.size !=0){
            linear_before_rest.visibility =View.GONE
            linearLayoutManager = LinearLayoutManager(context)
            mRecyclerView.layoutManager = linearLayoutManager
            adapter = CalendarAdapter(dayLists)
            mRecyclerView.adapter = adapter

            adapter!!.setCalendarListener(object : CalendarAdapter.CalendarListener {
                override fun selectCalendar(item: DayTable) {
                    dayDBDao!!.update(item)
                    var subFlagModels =  subFlagModelDao!!.getBySubId(item.subId)
                    val modelInfo = ModelInfo()
                    modelInfo.updateFlag = true

                    if(item.isTick){
                        modelInfo.updateCalendar = true
                        subFlagModels.tickNum  = subFlagModels.tickNum + 1
                    }else{
                        modelInfo.updateCalendar = false
                        subFlagModels.tickNum  = subFlagModels.tickNum - 1
                    }

                    subFlagModels.progress = subFlagModels.tickNum.toFloat()/subFlagModels.tick.toFloat()

                    var flagLists =  subFlagModelDao!!.getAllByFlagId(subFlagModels.fId)

                    var flagProgressList = subFlagModelDao!!.getAllByFlagIdAndProgress(subFlagModels.fId,1.0f,"提前完成")
                    var flagInfo =  flagModelDao!!.getById(subFlagModels.fId)
                    val sdf = SimpleDateFormat("yyyy/MM/dd")
                    var  completeToday = sdf.format(cal!!.time)
                    flagInfo.completeDay = completeToday
                    subFlagModels.completeDay = completeToday

                    if(flagLists.size == flagProgressList.size){
                        flagInfo.isComplete =  true

                        initFlagDoneDialog(1,flagInfo.title)
                    }else{
                        flagInfo.isComplete =  false
                        if(subFlagModels.progress == 1.0f || subFlagModels.status == "提前完成"){
                            initFlagDoneDialog(0,item.title)
                        }
                    }
                    //更新
                    flagModelDao!!.update(flagInfo)
                    subFlagModelDao!!.update(subFlagModels)

                    BusProvider.getBus().post(modelInfo)

                }
                override fun selectCalendarDate(item: DayTable) {
                    initUpdateTime(item)
                }
            })

        }else{
            linear_before_rest.visibility  = View.VISIBLE
        }
    }


    private var uiFlagDoneDialog: UIFlagDoneDialog? = null

    /**
     *  打卡完成弹窗
     */
    private fun initFlagDoneDialog(type:Int,title:String) {
        if (uiFlagDoneDialog == null) {
            uiFlagDoneDialog = UIFlagDoneDialog(context)


        }
        uiFlagDoneDialog!!.updateFlagDone(type,title);
        uiFlagDoneDialog!!.show()
    }


    private var weekDialog: UIUpdateTimeDialog? = null

    /**
     * 重复时间选择（星期和每天的时间节点）
     */
    private fun initUpdateTime(item: DayTable) {
        if (weekDialog == null) {
            weekDialog = UIUpdateTimeDialog(context)


        }
        weekDialog!!.setListener(object : UIUpdateTimeDialog.SimpleDateListener() {
            override fun onDateClicks(repeatTime: String) {
//                XLog.e("--subFlagModel--->>$repeatTime")
                item.repeatTime = repeatTime
                dayDBDao!!.update(item)
                updateCalendar()

            }
        })

        weekDialog!!.updateDate(item.repeatTime)
        weekDialog!!.show()
    }




}